<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
import echarts from 'echarts'
import resize from './mixins/resize'
require('echarts/theme/macarons') // echarts theme

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      json: [],
      datas: [],
      chart: null
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart()
    })
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')
      this.getAllDatas()
    },

    getAllDatas() {
      this.$axios.get('/api/test/phone/all').then(res => {
        // console.log(res.data.data)
        var arr = res.data.data
        for (let i = 0; i < arr.length; i++) {
          this.json.push({ value: arr[i].num, name: arr[i].name })
          this.datas.push(arr[i].name)
        }
        // console.log(JSON.parse(JSON.stringify(this.json)));
        // console.log(JSON.parse(JSON.stringify(this.datas)));
        this.setOptions()
      })
    },

    setOptions() {
      this.chart.setOption({
        xAxis: {
          type: 'category',
          data: this.datas
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: this.json,
            type: 'bar',
            showBackground: true,
            backgroundStyle: {
              color: 'rgba(220, 220, 220, 0.8)'
            }
          }
        ]
      })
    }
  }
}
</script>
